package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Api(tags = "通用接口")
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件访问 URL
     */
    @ApiOperation(value = "文件上传")
    @ApiImplicitParam(name = "file", value = "上传文件", required = true, paramType = "form", dataType = "MultipartFile")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.length() == 0) {
            return Result.error(MessageConstant.UPLOAD_FILE_NAME_IS_NULL);
        }
        int index = originalFilename.lastIndexOf(".");
        // 截取文件名
        String name = originalFilename.substring(0, index);
        // 截取拓展名
        String extension = originalFilename.substring(index);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 拼接唯一的文件名
        String objectName = name + "_" + now + extension;
        try {
            // 上传文件
            String path = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(path);
        } catch (IOException e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
